package com.goldplusgold.tradedelay.app.main.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.activity.BaseActivity;
import com.goldplusgold.support.lib.utils.StatusBarUtil;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.support.lib.widget.scroller.ViewPagerNoScroll;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.base.constant.IntentConstant;
import com.goldplusgold.tradedelay.app.home.fragment.HomeFragment;
import com.goldplusgold.tradedelay.app.main.adapter.MainPagerAdapter;
import com.goldplusgold.tradedelay.app.market.fragment.MarketFragment;
import com.goldplusgold.tradedelay.app.my.activity.UserActivity;
import com.goldplusgold.tradedelay.app.my.fragment.MyFragment;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;
import com.goldplusgold.tradedelay.app.trade.fragment.ContractTradeFragment;
import com.goldplusgold.tradedelay.app.trade.networkservice.TradeService;
import com.goldplusgold.tradedelay.app.trade.pojo.Switch;
import com.goldplusgold.ui.lib.keyboard.KeyboardUtil;

import butterknife.BindView;


public class TDMainActivity extends BaseActivity {

    @BindView(R.id.td_main_vp)
    public ViewPagerNoScroll mMainViewPager;
    @BindView(R.id.id_tab_home)
    RadioButton mTabHome;
    @BindView(R.id.id_tab_market)
    RadioButton mTabMarket;
    @BindView(R.id.id_tab_trade)
    public RadioButton mTabTrade;
    @BindView(R.id.id_tab_my)
    RadioButton mTabMy;
    @BindView(R.id.id_tab_menu)
    public RadioGroup mTabMenu;
    @BindView(R.id.id_root_layout)
    RelativeLayout mRootView;
    public MainPagerAdapter mAdapter;
    int mCurrentPosition;
    private final int LOGIN_REQUEST_CODE = 1;
    private KeyboardUtil keyboardUtil;
    private long mBackPressedTime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initMoveKeyBoard();
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_trade_delay_main;
    }

    public void initView() {
        mTabHome.setChecked(true);
        mTabMenu.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.id_tab_home:
                        mCurrentPosition = 0;
                        break;
                    case R.id.id_tab_market:
                        mCurrentPosition = 1;
                        break;
                    case R.id.id_tab_trade:
                        mCurrentPosition = 2;
                        break;
                    case R.id.id_tab_my:
                        mCurrentPosition = 3;
                        break;
                }
                if (mCurrentPosition == 2) {
                    new QuerySwitchStateTask().execute(AsyncTask.TYPE_NET);
                } else {
                    mMainViewPager.setCurrentItem(mCurrentPosition, false);
                }
            }

        });
        initAdapter();

        Intent intent = getIntent();
        if (intent.hasExtra(IntentConstant._TYPE)) {
            String type = getIntent().getStringExtra(IntentConstant._TYPE);
            if (TextUtils.equals("trade", type)) {
                mTabTrade.setChecked(true);
                mMainViewPager.setCurrentItem(2, false);
            }
        }
    }

    void initAdapter() {
        mAdapter = new MainPagerAdapter(getSupportFragmentManager(), this);
        mAdapter.add(HomeFragment.newInstance());
        mAdapter.add(MarketFragment.newInstance());
        mAdapter.add(ContractTradeFragment.newInstance());
        mAdapter.add(MyFragment.newInstance());

        mMainViewPager.setAdapter(mAdapter);
        mMainViewPager.setOffscreenPageLimit(3);
        mMainViewPager.setCurrentItem(0);
    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.setTranslucentForImageViewInFragment(TDMainActivity.this, null);
    }

    @Override
    public void onBackPressed() {


        if (keyboardUtil.isShow) {
            keyboardUtil.hideSystemKeyBoard();
            keyboardUtil.hideAllKeyBoard();
            keyboardUtil.hideKeyboardLayout();
        }
        // make sure it's not misuse, by pressing twice within 2 seconds.
        long currentTime = System.currentTimeMillis();
        if (mBackPressedTime == 0 || currentTime - mBackPressedTime > 2000) {
            mBackPressedTime = System.currentTimeMillis();
            showToastMessage("再次点击退出应用", Toast.LENGTH_LONG);
        } else if (currentTime - mBackPressedTime <= 2000) {
            super.onBackPressed();
            System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
            android.os.Process.killProcess(android.os.Process.myPid());   //获取PID
        }
    }

    private void initMoveKeyBoard() {
        keyboardUtil = new KeyboardUtil(this, mRootView);
    }

    public void showQuotationPage() {
        mMainViewPager.setCurrentItem(1, false);
        mTabMarket.setChecked(true);
    }

    public KeyboardUtil getKeyBoardUtil() {
        return keyboardUtil;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LOGIN_REQUEST_CODE && resultCode == RESULT_OK) {
            mTabTrade.setChecked(true);
            mMainViewPager.setCurrentItem(mCurrentPosition, false);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String type = intent.getStringExtra(IntentConstant._TYPE);
        if ("forceQuit".equals(type) || "wechatRegister".equals(type)) {
            mMainViewPager.setCurrentItem(3, false);
            mTabMy.setChecked(true);
        }

        if (TextUtils.equals("trade", type)) {
            mTabTrade.setChecked(true);
            mMainViewPager.setCurrentItem(2, false);
        }

    }


    public class QuerySwitchStateTask extends AsyncTask<Void, Void, Switch> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Switch doInBackground(Void... params) {
            Switch switchValue = null;
            try {
                switchValue = TradeService.getInstance().getSwitch();
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return switchValue;
        }

        @Override
        protected void onPostExecute(Switch switchValue) {
            super.onPostExecute(switchValue);
            if (switchValue == null) {
                return;
            }
            if (!switchValue.isSwitchFlag()) {
                mTabTrade.setChecked(true);
                mMainViewPager.setCurrentItem(mCurrentPosition, false);
            } else {
                if (!MyService.getInstance().isLogin()) {
                    Intent intent = new Intent(TDMainActivity.this, UserActivity.class);
                    startActivityForResult(intent, LOGIN_REQUEST_CODE);
                    overridePendingTransition(R.anim.slide_in_from_bottom, 0);
                    mTabHome.setChecked(true);
                } else {
                    mTabTrade.setChecked(true);
                    mMainViewPager.setCurrentItem(mCurrentPosition, false);
                }
            }
        }
    }

}
